package com.woniuxy.store.service.impl;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;



import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.store.infra.mapper.StoreContractMapper;
import com.woniuxy.store.infra.model.*;
import com.woniuxy.store.infra.model.Package;
import com.woniuxy.store.service.*;
import com.woniuxy.store.service.config.AlipayConfig;
import exception.MallException;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import result.CommonResultCodeEnum;

import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zz
 * @since 2023-07-20
 */
@Service
public class StoreContractServiceImpl extends ServiceImpl<StoreContractMapper, StoreContract> implements StoreContractService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private PackageFunctionService packageFunctionService;
    @Autowired
    private PackageService packageService;
    @Autowired
    private StoreWalletService storeWalletService;

    @Autowired
    private StoreInfoService storeInfoService;

    @Override
    public StoreContract addContract(Integer storeId, Integer packageFunctionId,String bankNum) {
        PackageFunction packageFunction = packageFunctionService.getById(packageFunctionId);
        if (packageFunction==null){
            throw new MallException("套餐不存在",CommonResultCodeEnum.INVALID_PARAM);
        }
        StoreInfo storeInfo = storeInfoService.getById(storeId);
        if (storeInfo==null){
            throw new MallException("没有该商家",CommonResultCodeEnum.INVALID_PARAM);
        }
        Package aPackage = packageService.getById(packageFunction.getPackageId());
        QueryWrapper<StoreContract> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id",storeId);
        queryWrapper.orderByDesc("pay_time");
        List<StoreContract> list = list(queryWrapper);
        StoreContract contract = new StoreContract();
        contract.setStoreId(storeId);
        contract.setPackageFunctionId(packageFunctionId);
        contract.setPayAmount(packageFunction.getFee());
        contract.setPayTime(new Date());
        contract.setPayYears(aPackage.getPayYears());
        contract.setPayState("CREATED");
        contract.setContractNum(IdUtil.getSnowflakeNextIdStr());
        if (list.size()==0){
            StoreWallet storeWallet = new StoreWallet();
            storeWallet.setStoreId(storeId);
            storeWallet.setStoreBalance(new BigDecimal("0"));
            storeWallet.setBankCardNumber(bankNum);
            storeWallet.setWithdrawalRate(0.006);
            storeWalletService.save(storeWallet);
            LocalDateTime expireTime = LocalDateTimeUtil.now().plusYears(contract.getPayYears());
            long milli = expireTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
            contract.setStoreWalletId(storeWallet.getStoreWalletId());
            contract.setExpirationTime(new Date(milli));
            contract.setStoreWalletId(storeWallet.getStoreWalletId());
            contract.setWithdrawalRate(storeWallet.getWithdrawalRate());
        }else {
            StoreContract storeContract = list.get(0);
            StoreWallet wallet = storeWalletService.getOne(new QueryWrapper<StoreWallet>().eq("store_id", storeId));
            contract.setStoreWalletId(wallet.getStoreWalletId());
            contract.setWithdrawalRate(wallet.getWithdrawalRate());
            long time = storeContract.getExpirationTime().getTime();
            long date = (long) contract.getPayYears()*365*24*60*60*1000+time;
            StoreWallet storeWallet = storeWalletService.getOne(new QueryWrapper<StoreWallet>().eq("store_id", storeInfo.getStoreId()));
            contract.setStoreWalletId(storeWallet.getStoreWalletId());
            contract.setExpirationTime(new Date(date));
        }
        save(contract);
        return contract;
    }

    @Override
    @GlobalTransactional
    public String payContract(String contractNum) throws AlipayApiException {
        StoreContract contract = getOne(new QueryWrapper<StoreContract>().eq("contract_num",contractNum));
        if (contract==null){
            throw new MallException("订单不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        if (!contract.getPayState().equals("CREATED")&&!contract.getPayState().equals("PAYING")){
            throw new MallException("订单不能支付", CommonResultCodeEnum.INVALID_PARAM);
        }
        contract.setPayState("PAYING");
        saveOrUpdate(contract);


        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = contract.getContractNum();
        //付款金额，必填
        String total_amount = contract.getPayAmount().setScale(2).toString();
        //订单名称，必填
        String subject = "商铺开通套餐支付";
        //商品描述，可空
        String body = contractNum;

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //添加一个主动检查支付状态的延迟消息队列
        Message<String> checkPay = MessageBuilder.withPayload(contract.getContractNum()).build();
        rocketMQTemplate.syncSend("pay_checks", checkPay,3000,6);

        //请求
        return alipayClient.pageExecute(alipayRequest).getBody();
    }




    @Override
    public void payCallback(StoreContract contract) {
        if (!contract.getPayState().equals("PAID")){
            contract.setPayState("PAID");
            save(contract);
        }

    }


    public String payOrderCheck(String num){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = num;
//        System.out.println(num+"-------------------");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getTradeStatus();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        return result;
    }
}
